import { GenerateDict } from "../modes/generate";
import { generateIconLayer, isIconMode } from "./icon";
import { generateLineLayer, isLineMode } from "./line";
import { generatePointLayer, isPointMode } from "./point";
import { generatePolygonLayer, isPolygonMode } from "./polygon";
import { generateTextLayer, isTextMode } from "./text";

// params = {map, mode, features}
export function renderFeatureLayer(params) {
	const { mode } = params;
	const modeType = getModeType(mode);

	let layerIds = [];

	switch (modeType) {
		case "point":
			layerIds = generatePointLayer(params);
			break;
		case "line":
			layerIds = generateLineLayer(params);
			break;
		case "polygon":
			layerIds = generatePolygonLayer(params);
			break;
		case "text":
			layerIds = generateTextLayer(params);
			break;
		case "icon":
			layerIds = generateIconLayer(params);
		default:
			break;
	}

	return layerIds;
}

export function updateFeatureLayer({ map, mode, layerIds, points }) {
	layerIds.forEach((layerId) => {
		const source = map.getSource(layerId);

		if (source) {
			const geojson = source._data;
			// console.log("geojson", geojson);

			const coords = GenerateDict[mode](points);
			const feature = geojson.features[0];
			feature.geometry.coordinates = coords;
			geojson.features.forEach((feature) => {
				feature.geometry.coordinates = coords;
			});
			source.setData(geojson);
		}
	});
}

// mapbox gl 绘制属性参考
// https://blog.csdn.net/weixin_48189070/article/details/125440455
// Layer properties 参考
// https://docs.mapbox.com/style-spec/reference/layers#layer-properties
// 样式数据保存在前端
// export function updateFeatureLayerStyles({ map, layerIds, styles }) {
//   // console.log("updateFeatureLayerStyles", layerIds, styles);
//   layerIds.forEach((layerId) => {
//     Object.entries(styles).forEach(([key, value]) => {
//       // 图层类型--fill/line/symbol
//       const isSame = layerId.includes(key.split("-")[0]);
//       if (isSame) {
//         const layout = ["text-field", "text-size", "icon-size"];
//         if (layout.includes(key)) {
//           map.setLayoutProperty(layerId, key, value);
//         } else {
//           map.setPaintProperty(layerId, key, value);
//         }
//       }
//     });
//   });
// }

// 样式数据保存在 geojson
export function updateFeatureLayerStyles({ map, layerIds, styles }) {
	// console.log("updateFeatureLayerStyles", layerIds, styles);
	layerIds.forEach((layerId) => {
		const source = map.getSource(layerId);
		const geojson = source._data;
		// console.log(geojson);

		geojson.features.forEach((feature) => {
			Object.entries(styles).forEach(([key, value]) => {
				feature.properties[key] = value;
			});
		});
		source.setData(geojson);
	});
}

export function getModeType(mode) {
	if (isPointMode(mode)) return "point";
	if (isLineMode(mode)) return "line";
	if (isPolygonMode(mode)) return "polygon";
	if (isTextMode(mode)) return "text";
	if (isIconMode(mode)) return "icon";
}
